package com.claire.jing.Aop;

import com.claire.jing.Annocation.Anyone;
import com.claire.jing.Common.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;

@Aspect
@Component
@Order(1)
public class AuthorityAspect {


    @Pointcut("execution(public * com.claire.jing.Controllers.*.*(..))")
    public void pointCut(){

    }

    @Around(value = "pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Annotation annotation = methodSignature.getMethod().getAnnotation(Anyone.class);
        //如果执行的方法有anyone的注解，则直接进入相应页面
        if (annotation != null){
            Object proceed = point.proceed();
            return proceed;
        }


        //如果没有anyOne的注解，则去判断有没有Session.先获取到Session
        HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        System.out.println("请求地址："+request.getPathInfo());
        HttpSession session = request.getSession(true);
        if (session.getAttribute("member") != null){
            Object proceed = point.proceed();
            return proceed;
        }

        Annotation responseBodyAnn = methodSignature.getMethod().getAnnotation(ResponseBody.class);
        //判断是否有responseBady的注解，如果有则返回Result类型
        if (responseBodyAnn != null){
            Result fail = Result.fail(String.class, -2, "未登陆！");
            return fail;

        }

        ModelAndView modelAndView =new ModelAndView();
        modelAndView.setViewName("redirect:/login");
        modelAndView.setViewName("redirect:/login");
        return modelAndView;

    }
}
